package com.yzg.simple.netty.chat.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * @ClassName NettyChatHandler
 * @Description TODO
 * @Authoe weiyan
 * @Date 2019/12/30 10:46
 * @Version 1.0
 **/
public class NettyChatClientHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(((ByteBuf) msg).toString(CharsetUtil.UTF_8));

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf = Unpooled.copiedBuffer("我知道了1", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                ctx.writeAndFlush(Unpooled.copiedBuffer(scanner.nextLine(),CharsetUtil.UTF_8));
            }
        }).start();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("异常产生："+cause.getMessage());
        ctx.close();
    }
}